import review from '@/models/review';
import dayjs from 'dayjs';
import { syncGetPersons, getHoliday } from '../personManage/index';

dayjs.locale('zh-cn');

// 获取review列表
export const getList = async (params) => {
  const judegDate = (time) => new Date().getTime() > time.getTime();
  const res = await review.getList(params, undefined, 1, 100);
  const arr: any = [];
  for (let j = 0; j < res.length; j += 1) {
    // 过期的就不要了
    if (!judegDate(new Date(`${res[j].time as string} 23:59:59`))) {
      arr.push(res[j]);
    }
  }
  const p = await syncGetPersons({ _id: '' });
  // 返回一轮的人员
  const { length } = p.filter((item) => item.weight);
  return arr.slice(0, length);
};

const deduplicate = (arr) => Array.from(new Set(arr));

const judegDate = (time) => new Date().getTime() > time.getTime();

// 生成review
const createReviewList = (index, date: string[], persons) => {
  const arr: any = [];
  let i = index;
  for (let j = 0; j < date.length; j += 1) {
    if (i >= persons.length) i = 0;
    if (!judegDate(new Date(`${date[j]} 23:59:59`))) {
      arr.push({
        time: date[j],
        name: persons[i],
      });
      i += 1;
    }
  }
  return arr;
};

// 获取节假期
const getHolidays = async () => {
  try {
    const r: any = await getHoliday();
    const h: string[] = [];
    for (let i = 0; i < r.length; i += 1) {
      const res = r[i].holiday;
      Object.keys(res).forEach((item) => {
        if (res[item].holiday) {
          h.push(`${r[i].year as string}-${item}`);
        }
      });
    }
    return h;
  } catch (err) {
    console.log(err);
    return [];
  }
};

// 获取日期
const creatWeeks = async (years) => {
  const holidays: any = await getHolidays();
  // 年月日是周五的
  let weeks5: string[] = [];
  for (let j = 0; j < years.length; j += 1) {
    const dayjs_year: any = dayjs(years[j]);
    const count = dayjs_year.isoWeeksInYear(); // 52
    for (let i = 0; i < count; i += 1) {
      weeks5.push(
        dayjs_year
          .week(i + 1)
          .isoWeekday(5)
          .format('YYYY-MM-DD'),
      );
    }
  }
  weeks5 = weeks5.filter((item) => !holidays.includes(item));
  return {
    weeks5: deduplicate(weeks5),
  };
};

// 获取本周是谁review，如果这个人正好被删除，那么往下周继续取
const getReviewName = async (persons) => {
  const dayjs_copy: any = dayjs();
  // dayjs().add(7, 'day')
  // 获取当前review列表
  const reviewList = await getList({});
  let index;
  function loop(date) {
    // 获取当前周
    const curWeek = date.format('YYYY-MM-DD');
    // 获取这周谁review
    const reviewName = reviewList.filter((item) => item.time === curWeek)[0].name;
    // 获取这个人在persons列表里的顺序
    index = persons.indexOf(reviewName);
    // 如果没找到，继续找下周的人
    if (index === -1) {
      loop(dayjs_copy.add(7, 'day').isoWeekday(5));
    }
  }
  loop(dayjs_copy.isoWeekday(5));
  return index;
};

// 往排期数据库里更新插入
const saveInDB = async (data) => {
  // 把原来排期删除
  await review.deleteMany({});
  const ret = await review.insertMany(data);
  return ret;
};

// 人员变动刷新review列表
export const refresh = async () => {
  // 获取所有人
  const res = await syncGetPersons({ _id: '' });
  const persons = res
    .filter((item) => item.weight)
    .sort((a, b) => Number(a.weight) - Number(b.weight))
    .map((item) => item.name);
  const index = await getReviewName(persons);
  // 获取周五
  const next_year = `${dayjs().add(1, 'year').year()}`;
  const { weeks5 } = await creatWeeks([new Date(), new Date(next_year)]);
  // 重新生成review
  const result = await createReviewList(index, weeks5 as string[], persons);
  // console.log(result);
  await saveInDB(result);
  return true;
};
